package com.geekyang.rabbitmqapi.message;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * @author geekyang
 * @date 2018/10/7 23:43
 * 生产消息
 */
public class Producer {

    public static void main(String[] args) throws IOException, TimeoutException {

        // 1.创建ConnectionFactory
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("39.106.128.50");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        // 2.从connectionFactory 中获取 connection
        Connection connection = connectionFactory.newConnection();

        // 3.通过connection 创建 channel
        Channel channel = connection.createChannel();

        // 自定义属性
        Map<String, Object> map = new HashMap<>();
        map.put("my1", 111);
        map.put("my2", 222);

        // 设置消息属性，链式操作
        AMQP.BasicProperties properties = new AMQP.BasicProperties().builder()
                .deliveryMode(2)    // 1 非持久化投递， 2 持久化投递
                .contentEncoding("UTF-8")
                .expiration("10000")  // 10s 过期时间
                .headers(map)  // 设置消息的自定义属性
                .build();

        // 4.通过channel发送数据
        for(int i=0; i < 5; i++){
            String msg = "Hello RabbitMQ.";
            channel.basicPublish("","test001", properties, msg.getBytes());
        }

        // 5.关闭连接
        channel.close();
        connection.close();
    }

}
